<?php
namespace Duobao\Model;

use Think\Model;
use Duobao\Controller\LogController as Mylog;

class MemberRecordModel extends Model{
    /**
     * Member Record model
     * use for: 用户的参与记录
     */

    protected $tableName = 'member_go_record';

    /**
     * 当前期数的的用户参与记录
     * 参数：商品id
     */
    public function inRecordOfGoods($id,$offset,$length){
        $condition = array();
        $condition['shopid'] = $id;
        //->limit($offset,$length)->getField('username,uphoto,uid,time,gonumber,ip')
        $result = $this->where($condition)->order('time desc')->field('username,uphoto,uid,time,gonumber,ip')->limit($offset,$length)->select();

        if($result){
            $tmp = array();
            foreach($result as $item){
                $tmp['username'] = $item['username'];
                $tmp['userimg'] = $item['uphoto'];
                $tmp['userid'] = $item['uid'];
                $tmp['time'] = date("Y-m-d H:i:s",$item['time']);
                $tmp['personNo'] = $item['gonumber'];#参与人次
                $tmp['userip'] = $item['ip'];
//                $tmp['address'] = R('Common/getAddressByIP',array($item['ip']));//将ip转换为地址
                $list[] = $tmp;
            }
        }else{
            return null;
        }

        return $list;
    }

    /**
     * 从商品入口获取用户的夺宝记录
     * 获取用户的参与记录
     * 包含其他用户进行中和已揭晓的商品
     */
    public function getOtherBuyRecord($uid,$offset,$length){
       #调用其他用户正在进行中的数据
        $result['underway'] = $this->getOtherRecoderUnderWay($uid,$offset,$length);
        $result['alreadyannounced'] = $this->getOtherAlreadyAnnounced($uid,$offset,$length);
        return $result;
    }

    /**
     * 获取其他用户的进行中的记录
     */
    private function getOtherRecoderUnderWay($uid,$offset,$length){
        #获取正在进行中的用户参与记录
        $model = new \Think\Model();
        $result = $model->query("select  __PREFIX__shoplist.id,__PREFIX__shoplist.title,__PREFIX__shoplist.thumb,__PREFIX__shoplist.zongrenshu,__PREFIX__shoplist.qishu,__PREFIX__shoplist.shenyurenshu from __PREFIX__shoplist INNER JOIN __PREFIX__member_go_record ON __PREFIX__shoplist.q_end_time is NULL AND __PREFIX__member_go_record.shopid = __PREFIX__shoplist.id  WHERE  __PREFIX__member_go_record.uid = ".$uid ." group by __PREFIX__member_go_record.shopid order by __PREFIX__member_go_record.time desc limit $offset,$length");

        if($result){
            #封装
            $tmp =array();
            foreach($result as $item){
                $tmp['goodsId'] = $item['id'];
                $tmp['goodsName'] = $item['title'];
                $tmp['goodsImg'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['thumb'];
                $tmp['periods'] = $item['qishu'];#期数
                $tmp['totalNeed'] = $item['zongrenshu'];#总需人数
                $tmp['need'] =$item['shenyurenshu'];#剩余人数

                #查找当前用户的参数次数与购买的号码
                $userResult = $model->query("select __PREFIX__member_go_record.gonumber from __PREFIX__member_go_record where uid=".$uid." and __PREFIX__member_go_record.shopid = ".$item['id']);

                #组合购买码
                if($userResult){
                    $tmp['count'] = 0;#清空购买数量
                    foreach($userResult as $val){
                        $tmp['count'] +=$val['gonumber'];
                    }
                }

                $list[] = $tmp;
            }
        }else{
            return null;
        }

        return $list;
    }

    /**
     * 获取其他用户已揭晓的参与记录
     */
    private function getOtherAlreadyAnnounced($uid,$offset,$length){
        #获取已揭晓的数据
        $model = new \Think\Model();
        $query = "select __PREFIX__shoplist.id,__PREFIX__shoplist.title,__PREFIX__shoplist.thumb,__PREFIX__shoplist.zongrenshu,__PREFIX__shoplist.qishu,__PREFIX__shoplist.q_end_time,__PREFIX__shoplist.q_user_code,__PREFIX__shoplist.q_uid,SUM(__PREFIX__member_go_record.gonumber) as gonumber  from __PREFIX__shoplist INNER JOIN __PREFIX__member_go_record ON __PREFIX__shoplist.id = __PREFIX__member_go_record.shopid AND __PREFIX__shoplist.q_end_time != '' WHERE __PREFIX__member_go_record.uid=".$uid." group by __PREFIX__shoplist.id order by __PREFIX__member_go_record.time desc limit $offset,$length";
        $result = $model->query($query);

        if($result){
            #封装
            $tmp =array();
            foreach($result as $item){
                $tmp['goodsId'] = $item['id'];
                $tmp['goodsName'] = $item['title'];
                $tmp['goodsImg'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['thumb'];
                $tmp['periods'] = $item['qishu'];#期数
                $tmp['endTime'] = date("Y-m-d H:i:s",$item['q_end_time']);#揭晓时间
                $tmp['lucklyCode'] = $item['q_user_code'];#中奖号码
                $tmp['buyNum'] = $item['gonumber'];#中奖用户购买数量
                #$tmp['lucklyMan'] = $item['username'];#中奖人姓名
                $tmp['lucklyManId'] = $item['q_uid'];#
                $tmp['totalNeed'] = $item['zongrenshu'];#总需人数

                #查找当前用户的参数次数与购买的号码
                $userResult = $model->query("select __PREFIX__member_go_record.gonumber from __PREFIX__member_go_record where uid=".$uid." and __PREFIX__member_go_record.shopid = ".$item['id']);
                #统计中奖用户的购买数量
                $lucklyMan = $model->query("select __PREFIX__member_go_record.gonumber from __PREFIX__member_go_record where uid=".$item['q_uid']." and __PREFIX__member_go_record.shopid = ".$item['id']);
                $condition['uid'] = $item['q_uid'];
                $tmp['lucklyMan'] = $model->table('__MEMBER__')->where($condition)->getField('username');
                if($lucklyMan){
                    $tmp["luncklyCount"] = 0;
                    foreach($lucklyMan as $val){
                        $tmp['luncklyCount'] += $val['gonumber'];
                    }
                }

                #组合购买码
                if($userResult){
                    $tmp['count'] = 0;
                    foreach($userResult as $val){
                        $tmp['count'] += $val['gonumber'];#当前用户购买的数量
                    }
                }

                $list[] = $tmp;
            }
        }else{
            return null;
        }
        return $list;
    }

    /**
     * 获取用户的中奖记录
     * #return goodsname,goodsimg,totalneed,qihao,luckynumber,inNumber,endtime
     */
    public function getUserWinRecord($uid,$offset,$length){
        $model = new \Think\Model();

        $result = $model->query("select  __PREFIX__shoplist.id, __PREFIX__shoplist.title,__PREFIX__shoplist.thumb,__PREFIX__shoplist.zongrenshu,__PREFIX__shoplist.qishu,__PREFIX__shoplist.q_user_code,__PREFIX__shoplist.q_end_time  from __PREFIX__shoplist INNER JOIN __PREFIX__member_go_record ON __PREFIX__shoplist.id = __PREFIX__member_go_record.shopid AND __PREFIX__shoplist.qishu = __PREFIX__member_go_record.shopqishu AND __PREFIX__member_go_record.huode != 0 WHERE __PREFIX__shoplist.q_uid='$uid' GROUP BY __PREFIX__member_go_record.shopid order by __PREFIX__member_go_record.time desc limit $offset,$length");

        if($result){

            $tmp = array();
            foreach($result as $item){
                $tmp['goodsid'] = $item['id'];#商品id
                $tmp['goodsname'] = $item['title'];#商品名称
                $tmp['goodsimg'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['thumb'];#商品的缩略图
                $tmp['totalNeed'] = $item['zongrenshu'];#总需人数
                $tmp['periodsNo'] = $item['qishu'];#期数
                $tmp['luckyNumber'] = $item['q_user_code'];#幸运号码
                $tmp['endTime'] = date("Y-m-d H:i:s",$item['q_end_time']);#结束时间

                #修改购买人次错误的问题
                $tmp['buyNumber'] = $model->query("select SUM(__PREFIX__member_go_record.gonumber) as gonumber from __PREFIX__member_go_record WHERE  __PREFIX__member_go_record.uid = ".$uid." and __PREFIX__member_go_record.shopid=".$item['id'])[0]['gonumber'];
                #$tmp['buyNumber'] = $item['buysum'];#购买人次
               # Mylog::write($model->getLastSql());
                $list[] = $tmp;
            }
        }else{
            return null;
        }

        return $list;
    }

    /**
     * 获取用户自己的个人中心的中奖记录
     */
    /**
     * 获取用户的中奖记录
     * #return goodsname,goodsimg,totalneed,qihao,luckynumber,inNumber,endtime
     */
    public function getMyWinRecord($uid,$offset,$length){
        $model = new \Think\Model();

        $result = $model->query("select  __PREFIX__member_go_record.status,__PREFIX__shoplist.id, __PREFIX__shoplist.title,__PREFIX__shoplist.thumb,__PREFIX__shoplist.zongrenshu,__PREFIX__shoplist.qishu,__PREFIX__shoplist.q_user_code,__PREFIX__shoplist.q_end_time from __PREFIX__shoplist INNER JOIN __PREFIX__member_go_record ON __PREFIX__shoplist.id = __PREFIX__member_go_record.shopid AND __PREFIX__shoplist.qishu = __PREFIX__member_go_record.shopqishu AND __PREFIX__member_go_record.huode != 0 WHERE __PREFIX__shoplist.q_uid='$uid' GROUP BY __PREFIX__member_go_record.shopid order by __PREFIX__member_go_record.time desc limit $offset,$length");

        if($result){

            $tmp = array();
            $tmp['sureShare'] = false;
            $tmp['areadyShare'] = false;
            foreach($result as $item){
                $tmp['goodsid'] = $item['id'];#商品id
                $tmp['goodsname'] = $item['title'];#商品名称
                $tmp['goodsimg'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['thumb'];#商品的缩略图
                $tmp['totalNeed'] = $item['zongrenshu'];#总需人数
                $tmp['periodsNo'] = $item['qishu'];#期数
                $tmp['luckyNumber'] = $item['q_user_code'];#幸运号码
                $tmp['endTime'] = date("Y-m-d H:i:s",$item['q_end_time']);#结束时间
                #$tmp['buyNumber'] = $item['buysum'];#购买人次
                $tmp['buyNumber'] = $model->query("select SUM(__PREFIX__member_go_record.gonumber) as gonumber from __PREFIX__member_go_record WHERE  __PREFIX__member_go_record.uid = ".$uid." and __PREFIX__member_go_record.shopid=".$item['id'])[0]['gonumber'];


                #获取当前商品的发货状态,即先在delivery表中查看是否用户绑定地址没，在去查看商品的发货状态
                $condition['uid'] = $uid;
                $condition['goods_id'] = $item['id'];
                $delivery = $model->table("__DELIVERY__")->where($condition)->find();
                if(!$delivery){
                    $tmp['deliveryStatus'] = '待确认收货地址';#用户没有绑定收货地址
                }else{
                    $status = explode(",",$item['status']);
                    if($status[1] == '未发货'){
                        $tmp['deliveryStatus'] = "已确认收货地址待发货";
                    }elseif($status[1] == "已发货"&& $status[2] == '待收货'){
                        #显示商品发送地址
                        $tmp['deliveryStatus'] = '已发货待确认收货';
                    }elseif($status[2] == "已完成"){
                        $tmp['deliveryStatus'] = '已完成';
                        #判断用户是否已经晒单
                        $condition2['sd_userid'] = $uid;
                        $condition2['sd_shopid'] = $item['id'];
                        $exist = $model ->table("__SHAIDAN__")->where($condition2)->find();
                        if(!$exist){
                            $tmp['sureShare'] = true;
                            $tmp['areadyShare'] = false;
                        }else{
                            $tmp['sureShare'] = false;
                            $tmp['areadyShare'] = true;
                        }
                    }

                    #判断订单是否完成
//                    if($status[2] == "已完成"){
//                        $tmp['deliveryStatus'] = '已完成';
//                        $tmp['sureShare'] = true;
//                    }
                }

                $list[] = $tmp;
                unset($tmp);
                unset($condition);
                unset($condition2);
            }
        }else{
            return null;
        }

        return $list;
    }

    /**
     * 获取用户夺宝记录的条数
     */
    public function getUserBuyCount($uid){
       $model = new \Think\Model();

        $result = $model->query("select count(__PREFIX__member_go_record.id) from __PREFIX__member_go_record WHERE __PREFIX__member_go_record.uid = '$uid' GROUP BY shopid");

        if(is_array($result)){
            $result = count($result);
        }

        return $result;
    }

    /**
     * 获取用户中奖记录的条数
     */
    public  function getUserWinCount($uid){
        $model = new \Think\Model();

        $result = $model->query("select count(__PREFIX__member_go_record.id) from __PREFIX__member_go_record WHERE __PREFIX__member_go_record.uid = '$uid'AND __PREFIX__member_go_record.huode != 0 GROUP BY shopid");

        if(is_array($result)){
            $result = count($result);
        }

        return $result;
    }

    /**
     * 用户充值记录
     */
    public function getUserPayRecord($uid,$offset,$length){
        $model = new \Think\Model();
        $status = "已付款";

        #在go_member_go_record中只有用户购买的记录，现在需要添加用户微信的充值记录
        #改变逻辑
        #$result = $this->field('pay_type,time,moneycount')->where($condition)->order('time desc')->limit($length,$offset)->select();
        $result = $model->query("select `pay_type`,`time`,`money` from __PREFIX__member_addmoney_record where uid=".$uid." and status = '已付款' order by `time` desc limit ".$offset.','.$length);
       if($result){

           $tmp = array();
           foreach($result as $item){
               $tmp['paytype'] = $item['pay_type'];#支付类型

               $tmp['paytime'] = date('Y-m-d H:i:s',$item['time']);#支付时间
               $tmp['amount'] = $item['money'];#金额

               $list[] = $tmp;
           }
       }

        return $list;
    }

    /**
     * 获取用户自身的参与记录
     */
    public function getMyIndiana($uid,$offset,$length){
        #先给前端未揭晓的数据，再给已揭晓的数据
        $result['underway'] = $this->getMyUnderway($uid,$offset,$length);
        if(!$result['underway']){
            $result['complete'] = $this->getMyAlreadyAnnounced($uid,$offset,$length);
        }else{
            $result['complete'] = $this->getMyAlreadyAnnounced($uid,$offset,$length-count($result['underway']));
        }
        return $result;

    }

    /**
     * 获取用户自身的参与记录中的正在进行中的
     */
    public function getMyUnderway($uid,$offset,$length){
        #获取正在进行中的用户参与记录
        $model = new \Think\Model();
        $result = $model->query("select  __PREFIX__shoplist.id,__PREFIX__shoplist.title,__PREFIX__shoplist.thumb,__PREFIX__shoplist.zongrenshu,__PREFIX__shoplist.qishu,__PREFIX__shoplist.shenyurenshu from __PREFIX__shoplist INNER JOIN __PREFIX__member_go_record ON __PREFIX__shoplist.q_end_time is NULL AND __PREFIX__member_go_record.shopid = __PREFIX__shoplist.id  WHERE  __PREFIX__member_go_record.uid = ".$uid ." group by __PREFIX__member_go_record.shopid order by __PREFIX__member_go_record.time desc limit $offset,$length");

        if($result){
            #封装
            $tmp =array();
            foreach($result as $item){
                $tmp['goodsId'] = $item['id'];
                $tmp['goodsName'] = $item['title'];
                $tmp['goodsImg'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['thumb'];
                $tmp['periods'] = $item['qishu'];#期数
                $tmp['totalNeed'] = $item['zongrenshu'];#总需人数
                $tmp['need'] =$item['shenyurenshu'];#剩余人数

                #查找当前用户的参数次数与购买的号码
                $userResult = $model->query("select __PREFIX__member_go_record.gonumber,__PREFIX__member_go_record.goucode from __PREFIX__member_go_record where uid=".$uid." and __PREFIX__member_go_record.shopid = ".$item['id']);

                #组合购买码
                if($userResult){
                        $tmp['code'] = '';
                        $tmp['count'] = 0;#清空购买数量
                    foreach($userResult as $val){
                        $tmp['count'] +=$val['gonumber'];
                        $tmp['code'] .= $val['goucode'];
                        $tmp['code'] .= ',';
                    }
                }

                $list[] = $tmp;
            }
        }else{
            return null;
        }

        return $list;
    }

    /**
     * 获取用户自身的参与记录中已经揭晓的
     */
    public function getMyAlreadyAnnounced($uid,$offset,$length){
        #获取已揭晓的数据
        $model = new \Think\Model();
        $query = "select __PREFIX__shoplist.id,__PREFIX__shoplist.title,__PREFIX__shoplist.thumb,__PREFIX__shoplist.zongrenshu,__PREFIX__shoplist.qishu,__PREFIX__shoplist.q_end_time,__PREFIX__shoplist.q_user_code,__PREFIX__shoplist.q_uid,SUM(__PREFIX__member_go_record.gonumber) as gonumber  from __PREFIX__shoplist INNER JOIN __PREFIX__member_go_record ON __PREFIX__shoplist.id = __PREFIX__member_go_record.shopid AND __PREFIX__shoplist.q_end_time != ''  WHERE __PREFIX__member_go_record.uid=".$uid." group by __PREFIX__shoplist.id order by __PREFIX__member_go_record.time desc limit $offset,$length";
        $result = $model->query($query);

        if($result){
            #封装
            $tmp =array();
            foreach($result as $item){
                $tmp['goodsId'] = $item['id'];
                $tmp['goodsName'] = $item['title'];
                $tmp['goodsImg'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['thumb'];
                $tmp['periods'] = $item['qishu'];#期数
                $tmp['endTime'] = date("Y-m-d H:i:s",$item['q_end_time']);#揭晓时间
                $tmp['lucklyCode'] = $item['q_user_code'];#中奖号码
                $tmp['buyNum'] = $item['gonumber'];#中奖用户购买数量
                $tmp['lucklyManId'] = $item['q_uid'];#中奖人id
                #$tmp['lucklyMan'] = $item['username'];#中奖人姓名
                $tmp['totalNeed'] = $item['zongrenshu'];#总需人数

                #查找当前用户的参数次数与购买的号码
                $userResult = $model->query("select __PREFIX__member_go_record.gonumber,__PREFIX__member_go_record.goucode from __PREFIX__member_go_record where uid=".$uid." and __PREFIX__member_go_record.shopid = ".$item['id']);
                #统计中奖用户的购买数量
                $lucklyMan = $model->query("select SUM(__PREFIX__member_go_record.gonumber) as gocount from __PREFIX__member_go_record where uid=".$item['q_uid']." and __PREFIX__member_go_record.shopid = ".$item['id']);
                $condition['uid'] = $item['q_uid'];
                $tmp['lucklyMan'] = $model->table('__MEMBER__')->where($condition)->getField('username');
                if($lucklyMan){
                    $tmp['luncklyCount'] = $lucklyMan[0]['gocount'];
                }

                #组合购买码
                if($userResult){
                        $tmp['code'] ='';#清空tmp['code'];
                        $tmp['count'] = 0;
                    foreach($userResult as $val){
                        $tmp['count'] += $val['gonumber'];
                        $tmp['code'] .=  $val['goucode'];
                    }
                }

                if($tmp['lucklyManId'] == $uid){
                    #当前期商品的中奖用户是当前用户
                    #步骤1，查询delivery表，当前的用户的地址是否已经绑定
                    $condition2['goods_id'] = $tmp['goodsId'];
                    $condition2['uid'] = $uid;
                    $deliveryResult = $model->table("__DELIVERY__")->where($condition2)->find();
                    #如果用户没有选择收货地址,状态
                    if(!$deliveryResult){
                        $tmp['delivery']['status'] = false;#false表示用户没有选择收货地址
                    }else{
                        $tmp['delivery']['status'] = true;
                    }
                }

                $list[] = $tmp;
            }
        }else{
            return null;
        }
        return $list;
    }
    /* end of Member record */
}

